package edu.hrbu.trade01.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hrbu.trade01.entity.Role;
import edu.hrbu.trade01.entity.UserRole;
import edu.hrbu.trade01.mapper.RoleMapper;
import edu.hrbu.trade01.service.RoleService;
import edu.hrbu.trade01.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 徐登宇
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserRoleService userRoleService;

    // 条件分页查询
    @Override
    public Page<Role> getPageWithCondition(int page, int limit, String nameStr) {
        Page<Role> pageParam = new Page<>(page, limit);
        // 获取角色列表
        LambdaQueryWrapper<Role> wrapperRole = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(nameStr)) {
            Role role = JSONUtil.toBean(nameStr, Role.class);
            if (role != null) {
                String name = role.getName();
                LocalDateTime createTime = role.getCreateTime();
                LocalDateTime updateTime = role.getUpdateTime();
                if (!ObjectUtils.isEmpty(name))
                    wrapperRole.like(Role::getName, name);
                if (!ObjectUtils.isEmpty(createTime))
                    wrapperRole.ge(Role::getCreateTime, createTime);
                if (!ObjectUtils.isEmpty(updateTime))
                    wrapperRole.le(Role::getUpdateTime, updateTime);
            }

        }

        return page(pageParam, wrapperRole);
    }

    // 获取所有的角色以及自己所拥有的角色
    @Override
    public HashMap<String, List<Role>> getRoleMapByUserId(Long userId) {
        List<Role> allRoleList = list();

        LambdaQueryWrapper<UserRole> wrapperUserRole = new LambdaQueryWrapper<>();
        wrapperUserRole.eq(UserRole::getUserId, userId);
        List<Long> ownRoleIdList = userRoleService.list(wrapperUserRole).stream().map(UserRole::getRoleId).collect(Collectors.toList());

        ArrayList<Role> ownRoleList = new ArrayList<>();
        for (Role r : allRoleList) {
            if (ownRoleIdList.contains(r.getId()) && r.getIsDeleted() == 0) ownRoleList.add(r);
        }

        HashMap<String, List<Role>> map = new HashMap<>();
        map.put("ownRoleList", ownRoleList);
        map.put("allRoleList", allRoleList);

        return map;
    }

    // 重新分配角色
    @Transactional
    @Override
    public void toAssign(List<Long> ids, Long userId) {
        // 先删除先前的角色
        LambdaQueryWrapper<UserRole> wrapperUserRole = new LambdaQueryWrapper<>();
        wrapperUserRole.eq(UserRole::getUserId, userId);
        userRoleService.remove(wrapperUserRole);
        // 添加新分配的角色
        for (Long roleId:ids) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            userRoleService.save(userRole);
        }
    }

    @Override
    public boolean check(Role role) {
        LambdaQueryWrapper<Role> wrapperRole = new LambdaQueryWrapper<>();
        // 判断roleId是否为空，空就是save，否则就是update
        if (role.getId()!=null){
            wrapperRole.ne(Role::getId, role.getId());
        }
        // 角色名不能相同
        wrapperRole.eq(Role::getName, role.getName());
        return getOne(wrapperRole)==null;
    }
}
